package com.isoftstone.project.system.service.impl;


import com.isoftstone.common.BusinessException;
import com.isoftstone.common.utils.StringUtils;
import com.isoftstone.framework.domain.Page;
import com.isoftstone.project.system.domain.SysDepartment;
import com.isoftstone.project.system.mapper.SysDepartmentMapper;
import com.isoftstone.project.system.mapper.SysUserRoleMapper;
import com.isoftstone.project.system.service.IDepartMentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 16/5/16.
 * 部门
 */

@Service
public class DepartMentService implements IDepartMentService {

    @Autowired
    SysDepartmentMapper departmentMapper;
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Transactional
    public void saveDept(SysDepartment department) throws Exception {
        departmentMapper.saveDept(department);
    }

    @Transactional
    public void updateDept(SysDepartment department) throws Exception {
        departmentMapper.updateDept(department);
    }

    @Transactional
    public String deleteDept(String deptId) throws Exception {
        String result = null;
        //判断下面是否有子部门，如果有请先删除子部门
        List<String> list = departmentMapper.getDeptIdByparentId(deptId);
        if(list.isEmpty()) {
            ////判断部门下是否有用户
            result="OK";
        }else{
            result = "请先删除子部门!";
        }
        return result;
    }

    @Override
    public void  deleteDept1(String deptId) throws Exception {
        departmentMapper.deleteDept(deptId);
    }

    public List<SysDepartment> getDeptAll(String deptId) throws Exception {
        return departmentMapper.getDeptAll(deptId);
    }

    public List<SysDepartment> getSysDeptlistPage(Page page) throws Exception {
        return departmentMapper.getSysDeptlistPage(page);
    }

    public SysDepartment getDeptById(String deptId) throws Exception {
        return departmentMapper.getDeptById(deptId);
    }

    @Override
    public List<SysDepartment> getDeptByName(String deptName) throws Exception {
        return departmentMapper.getDeptByName(deptName);
    }

    public List<String> getDeptByparentId(String parentId) throws  Exception{
        List<String> list = new ArrayList<>();
        //包含本部门
        list.add(parentId);
        getSongDeptId(list,parentId);
        return list;
    }

    @Override
    public List<String> getDeptUids(List<String>  deptIds) throws Exception {
        return departmentMapper.getDeptUids(deptIds);
    }

    @Override
    public List<Map<String, Object>> getRestDeptlistPage(Page page) {
        return departmentMapper.getRestDeptlistPage(page);
    }

    @Override
    public String impDepartment(List<SysDepartment> departmentList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(departmentList) || departmentList.size() == 0) {
            throw new BusinessException("导入数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysDepartment dept : departmentList) {
            try {

                SysDepartment id = this.getDeptById(dept.getDeptId());
                // 验证是否存在这个用户
                if (StringUtils.isNull(id)) {
                    dept.setCreateBy(operName);
                    dept.setCreateTime(new Date());
                    this.saveDept(dept);
                    successNum++;
                    successMsg.append("<br/>第" + successNum + " 导入成功");
                } else if (updateSupport) {
                    dept.setUpdateBy(operName);
                    dept.setUpdateTime(new Date());
                    this.updateDept(dept);
                    successNum++;
                    successMsg.append("<br/>第" + successNum + "行更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>第" + failureNum + "行导入失败数据已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>第" + failureNum + "行导入失败：" ;
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 递归获取所有子孙部门
     * @param list
     * @param deptId
     * @return
     * @throws Exception
     */
    public List<String> getSongDeptId(List<String> list,String deptId) throws Exception {
        List<String> list1= departmentMapper.getDeptIdByparentId(deptId);
        if(!(list1.isEmpty())){
            for(String str:list1){
                list.add(str);
                getSongDeptId(list,str);
            }
            return  list;
        }else {
            return  list;
        }
    }

}
